package com.kou.backend.service.impl.user;

import cn.hutool.core.util.CharsetUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kou.backend.dao.UserInfoDao;
import com.kou.backend.dto.user.UserDetailSecurityDTO;
import com.kou.backend.entity.UserInfoDO;
import com.kou.backend.error.CommonErrorEnum;
import com.kou.backend.exception.CommonException;
import com.kou.backend.request.user.SaveUserReqDTO;
import com.kou.backend.service.UserInfoService;
import com.kou.backend.utils.MD5EncryptionUtil;
import com.kou.backend.utils.SecureRandomUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * @author Kou
 * @description 针对表【op_user_info(用户表)】的数据库操作Service实现
 * @createDate 2023-08-29 19:32:21
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, UserInfoDO> implements UserInfoService {
    @Resource
    private UserInfoDao userInfoDao;

    @Override
    public void saveUser(SaveUserReqDTO reqDTO) {
        UserInfoDO userInfoDO = new UserInfoDO();
        if (StringUtils.isBlank(reqDTO.getId())) {
            UserInfoDO userAccount = userInfoDao.selectOne(new QueryWrapper<UserInfoDO>().eq("user_account", reqDTO.getUserAccount()));
            if (Objects.nonNull(userAccount)) {
                throw new CommonException(CommonErrorEnum.ERROR_USER_ACCOUNT_REPEAT);
            }
            //生成4位随机盐值及userId
            userInfoDO.setSalt(SecureRandomUtils.generateFourNum());
            userInfoDO.setUserId(UUID.randomUUID().toString().replace("-", ""));
            userInfoDO.setUserAccount(reqDTO.getUserAccount());
            buildUserBaseInfo(reqDTO, userInfoDO);
            userInfoDO.setPassword(MD5EncryptionUtil.sign(reqDTO.getPassword(),
                    userInfoDO.getSalt(), CharsetUtil.UTF_8));
            userInfoDao.insert(userInfoDO);
        } else {
            userInfoDO.setId(Long.valueOf(reqDTO.getId()));
            buildUserBaseInfo(reqDTO, userInfoDO);
            userInfoDao.updateById(userInfoDO);
        }
    }

    @Override
    public UserDetails loadUserByUserId(String account) {
        //KouTODO:2023/8/31 20:33 kou 角色权限管理完善后需修改
        UserInfoDO userInfoDO = Optional.ofNullable(userInfoDao.selectOneByAccountEffective(account, "1"))
                .orElseThrow(() -> new UsernameNotFoundException("管理平台未添加该用户，请联系管理员添加"));
        return new UserDetailSecurityDTO(userInfoDO, Collections.singletonList("all"));
    }

    private static void buildUserBaseInfo(SaveUserReqDTO reqDTO, UserInfoDO userInfoDO) {
        userInfoDO.setUserName(reqDTO.getUserName());
        userInfoDO.setPhone(reqDTO.getPhone());
        userInfoDO.setEmail(reqDTO.getEmail());
    }
}




